package com.iepacj.mina;

import com.alibaba.fastjson.JSONObject;
import org.bson.ByteBuf;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by iEpac on 16/6/18.
 */
public class MinaTest {

    public static void main(String[] args) throws IOException {

        String[] mids = new String[]{"17080032629", "17080032630"};

        for (String mid : mids) {

            final SocketChannel sc = SocketChannel.open();

            boolean connect = sc.connect(new InetSocketAddress("127.0.0.1", 4001));
            System.out.println("connect" + connect);

            JSONObject j = new JSONObject();
            j.put("mt", 1);
            j.put("mid", mid);

            ByteBuffer src = ByteBuffer.allocate(1024);
            src.put((j.toJSONString() + "\n").getBytes());
            src.flip();
            int w = sc.write(src);
            System.out.println("发送 :: " + j.toJSONString() + " :: " + w);

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            final String fMid = mid;
            Timer t = new Timer("heartbeat");
            t.schedule(new TimerTask() {
                @Override
                public void run() {
                    JSONObject j = new JSONObject();
                    j.put("mt", 2);
                    j.put("mid", fMid);

                    ByteBuffer src = ByteBuffer.allocate(1024);
                    src.put((j.toJSONString() + "\n").getBytes());
                    System.out.println("发送心跳");
                    try {
                        src.flip();
                        sc.write(src);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }, 1000, 10000);
        }

    }



}
